//
//  FlutterNativeAliPayPlugin.m
//  Runner
//
//  Created by 小二同學 on 2020/4/9.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "FlutterNativeAliPayPlugin.h"
#import <AlipaySDK/AlipaySDK.h>
#import <objc/runtime.h>

@interface FlutterNativeAliPayPlugin()

@property (nonatomic, strong) UIViewController *controller;
@end

@implementation FlutterNativeAliPayPlugin
static NSString *const CHANNELNAME = @"com.ahj/aliPayPlugin";
static NSString *const METHODNAME  = @"aliPay";

static char *resultKey      = "resultKey";

/**
 *plugin 注册
 */
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    channel = [FlutterMethodChannel methodChannelWithName:CHANNELNAME binaryMessenger:[registrar messenger]];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    FlutterNativeAliPayPlugin *plugin = [[FlutterNativeAliPayPlugin alloc]initWithViewController:viewController];
    
    [registrar addMethodCallDelegate:plugin channel:channel];
}

/**
 *flutter端通过通道调用原生方法时会进入以下回调
 */
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    
    if ([call.method isEqualToString:METHODNAME]) {
        
        NSDictionary *dic = call.arguments;

        [[AlipaySDK defaultService] payOrder:dic[@"sign"] fromScheme:@"com.anHuanJia.xinanli" callback:^(NSDictionary *resultDic) {
            self.result = result;
            if ([resultDic[@"resultStatus"]intValue] == 9000) {
                result(@"1");
            }else if ([resultDic[@"resultStatus"]intValue] == 4000 || [resultDic[@"resultStatus"]intValue] == 6002 || [resultDic[@"resultStatus"]intValue] == 6001) {
                result(@"1");
            }else {
                result(@"1");
            }
        }];
    } else {
        result(FlutterMethodNotImplemented);
    }
}

- (void)result:(NSNotification *)no {
    NSString *resultStatus = no.object;
    if ([resultStatus intValue] == 9000) {
        [channel invokeMethod:@"aliPayResult" arguments:@"1"];
    }else if ([resultStatus intValue] == 4000 || [resultStatus intValue] == 6002 || [resultStatus intValue] == 6001) {
        [channel invokeMethod:@"aliPayResult" arguments:@"1"];
    }else {
        [channel invokeMethod:@"aliPayResult" arguments:@"1"];
    }
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(result:) name:@"aliPay" object:nil];
    }
    return self;
}

- (void)setResult:(FlutterResult)result {
    objc_setAssociatedObject(self, resultKey, result, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (FlutterResult)result{
    return objc_getAssociatedObject(self, resultKey);
}
@end
